package com.zhjhserver.utils;

import java.util.ArrayList;

import net.sf.json.JSONObject;

public class Hall
{
    // 房间：初级场、中级场、高级场、会员场、私人场
    private static final int ROOM_NUM = 5;

    private static final int ROOM_LOW = 0;
    private static final int ROOM_MID = 1;
    private static final int ROOM_HIGH = 2;
    private static final int ROOM_MEMBER = 3;
    private static final int ROOM_PRIVATE = 4;

    //private int mIndex = 0;
    private ArrayList<Room> mRoomList = null;
    private Object mSeatSynch = new Object();

    public Hall()
    {
        mRoomList = new ArrayList<Room>();

        for (int i=0; i<ROOM_NUM; i++)
        {
            Room room = new Room(this, i);
            mRoomList.add(room);
        }
    }

    /*****************************************************
	 * 快速找座位: 1. 一人只能占一个位置, 2. 此位原本是空位
	 * @param jsonText
	 * @return
	 */
	public String fastFindSeat(Player player)
	{
	    synchronized(mSeatSynch)
        {
    	    Seat seat = null;

    	    // 获取此玩家能进入的房间

            // 找座位
    	    if (true)
    	    {
    	        // 初级场
    	        seat = mRoomList.get(ROOM_LOW).fastFindSeat();
    	    }

    	    if (seat==null && true)
    	    {
    	        // 中级场
    	        seat = mRoomList.get(ROOM_MID).fastFindSeat();
    	    }

    	    if (seat==null && true)
    	    {
    	        // 高级场
    	        seat = mRoomList.get(ROOM_HIGH).fastFindSeat();
    	    }

    	    return seatDown(player, seat);
    	}
	}

	private String seatDown(Player player, Seat seat)
	{
	    int error = Const.ERROR_UNKOWN;
	    int hallId = 0;
        int roomId = 0;
        int tableId = 0;
        int seatId = 0;
		JSONObject jsonOut = new JSONObject();

	    if (seat == null)
	    {
	        error = Const.ERROR_NO_SEAT;
	    }
	    else
	    {
	        error = Const.ERROR_SUCCESS;
	        player.setSeat(seat);

	        Table table = seat.getTable();
	        roomId = table.getRoom().getIndex();
	        tableId = table.getIndex();
	        seatId = seat.getIndex();

    		jsonOut.put("hall_id", hallId);
    		jsonOut.put("room_id", roomId);
    		jsonOut.put("table_id", tableId);
    		jsonOut.put("seat_id", seatId);

	        String tableInfo = table.getInfo();
	        jsonOut.put("table_info", tableInfo);
	    }

		jsonOut.put("error", error);

		return jsonOut.toString();
	}

	public void notifySameTable(Player player, int funcId)
	{
	    // 通知同桌其他玩家有玩家的状态变化
    	Seat seat = player.getSeat();

    	if (seat != null)
    	{
    	    seat.getTable().notify(player, funcId);
    	}
	}
}
